import { useEffect } from "react";
import { useReactive } from "ahooks";
import { useModel } from "umi";
import { message } from "antd";

export default function gatewayInfoModal() {
    const { remoteData } = useModel("global");
    const { baseInfo } = useModel("person.info");

    const state = useReactive({
        gatewayLoading: false,
        organizationLoading: false,
        gateways: [],
        selectedGateway: {},
        organizations: [],
        selectedOrganization: {},
        organizationServices: [],
    });

    const loadGateways = async () => {
        state.gatewayLoading = true;
        try {
            let gateways = await localforage.getItem("myManagedGateways-" + baseInfo.uuid);
            if (gateways && gateways.length) {
                state.gateways = gateways;
                state.selectedGateway = gateways[0];
                handleSelectedGateway(gateways[0]);
            }
        } catch (err) {}
        state.gatewayLoading = false;
    };

    useEffect(() => {
        loadGateways();
    }, [baseInfo.uuid]);

    const loadOrganizations = async () => {
        state.organizationLoading = true;
        let res = await remoteData({
            object: "multi-organization-gateway",
            serviceUrl: state.selectedGateway.url,
            serviceName: "/api/v1/organization/getAll",
            params: {},
        });
        state.organizations = res || [];
        state.selectedOrganization.uuid && (state.selectedOrganization = state.organizations.find((item) => state.selectedOrganization.uuid === item.uuid));
        state.organizationLoading = false;
    };

    useEffect(() => {
        state.selectedGateway?.url && loadOrganizations();
    }, [state.selectedGateway]);

    const loadOrganizationServices = async () => {
        let res = await remoteData({
            object: "multi-organization-gateway",
            serviceUrl: state.selectedGateway.url,
            serviceName: "/api/v1/organization/getServices",
            organizationUuid: state.selectedOrganization.uuid,
            params: { uuid: state.selectedOrganization.uuid },
        });
        state.organizationServices = res || [];
    };

    useEffect(() => {
        if (state.selectedOrganization?.uuid) {
            loadOrganizationServices();
        }
    }, [state.selectedOrganization]);

    const setCurrentGateway = (gateway) => {
        state.selectedGateway = gateway;
    };

    const setCurrentOrganization = (organization) => {
        state.selectedOrganization = organization;
    };

    const updateSelectedOrganization = (newData) => {
        let data = state.organizations.slice();
        let index = data.findIndex((item) => state.selectedOrganization.uuid === item.uuid);
        if (index !== -1) {
            data[index] = { ...data[index], ...newData };
            state.selectedOrganization = { ...state.selectedOrganization, ...newData };
            state.organizations = data;
        }
    };

    const updateOrganizationStatus = async (data) => {
        let items = state.organizationServices.filter((item) => item.serviceRunning === true);
        if (data.usageStatus === true && items.length === 0) return message.error("没有正在运行的数据服务, 不能启用组织");
        if (data.usageStatus === false && items.length > 0) return message.error("有正在运行的数据服务, 不能停用组织");
        let res = await remoteData({
            object: "multi-organization-gateway",
            serviceUrl: state.selectedGateway.url,
            serviceName: "/api/v1/organization/updateStatus",
            organizationUuid: state.selectedOrganization.uuid,
            params: { uuid: state.selectedOrganization.uuid, data },
        });
        if (res) {
            message.success("成功更新组织状态信息");
            updateSelectedOrganization(data);
        }
    };

    const asyncOrganizationInfo = async () => {
        let res = await remoteData({
            object: "base-platform-management-service",
            serviceName: "/api/v1/organization/getFullInfo",
            params: { uuid: state.selectedOrganization.uuid },
        });
        if (res) {
            let data = {
                fullName: res.baseInfo.fullName,
                shortName: res.baseInfo.shortName,
                industryType: res.industryTypes,
                superAdministratorUuid: res.baseInfo.superAdministratorUuid,
                superAdministratorName: res.baseInfo.superAdministratorName,
                databaseDeployMode: res.baseInfo.databaseDeployMode,
                dependentedDatabases: res.baseInfo.dependentedDatabases,
            };
            res = await remoteData({
                object: "multi-organization-gateway",
                serviceUrl: state.selectedGateway.url,
                serviceName: "/api/v1/organization/update",
                organizationUuid: state.selectedOrganization.uuid,
                params: { uuid: state.selectedOrganization.uuid, data },
            });
            if (res) {
                message.success("成功同步组织信息");
                state.selectedOrganization = { ...state.selectedOrganization, ...data };
                loadOrganizations();
            }
        }
    };

    const deleteOrganization = async () => {
        if (state.selectedOrganization.uuid) {
            let res = await remoteData({
                object: "multi-organization-gateway",
                serviceUrl: state.selectedGateway.url,
                serviceName: "/api/v1/organization/destroy",
                organizationUuid: state.selectedOrganization.uuid,
                params: { uuid: state.selectedOrganization.uuid },
            });
            if (res) {
                await loadOrganizations();
                state.selectedOrganization = {};
            }
        }
    };

    const resetInit = async () => {
        if (state.selectedOrganization.uuid) {
            let res = await remoteData({
                object: "multi-organization-gateway",
                serviceUrl: state.selectedGateway.url,
                serviceName: "/api/v2/organization/resetInitialization",
                organizationUuid: state.selectedOrganization.uuid,
                params: { uuid: state.selectedOrganization.uuid },
            });
            if (res) {
                updateSelectedOrganization({ initializationStatus: false, initializationTime: null });
            }
        }
    };

    const changeServiceStatus = async (serviceUuid, serviceStatus) => {
        const { databaseUser, databasePassword } = state.selectedOrganization;

        if (serviceStatus === true) {
            if (!databaseUser || !databasePassword) return message.warning("没有正确设置组织数据库信息，不能启用组织数据服务");
        }

        let res = await remoteData({
            object: "multi-organization-gateway",
            serviceUrl: state.selectedGateway.url,
            serviceName: "/api/v2/organization/updateGraphqlServiceStatus",
            organizationUuid: state.selectedOrganization.uuid,
            params: { serviceUuid, serviceStatus },
        });
        if (res) {
            message.success("成功更改组织数据服务状态");
            loadOrganizationServices();
        }
    };

    const stopService = async (serviceUuid) => {
        let res = await remoteData({
            object: "multi-organization-gateway",
            serviceUrl: state.selectedGateway.url,
            serviceName: "/organization/singleDatabaseMode/stopService",
            organizationUuid: state.selectedOrganization.uuid,
            params: { serviceUuid },
        });
        if (res) {
            message.success("组织数据服务已停止运行");
            loadOrganizationServices();
        }
    };

    const deleteService = async (serviceUuid) => {
        let res = await remoteData({
            object: "multi-organization-gateway",
            serviceUrl: state.selectedGateway.url,
            serviceName: "/organization/singleDatabaseMode/deleteService",
            organizationUuid: state.selectedOrganization.uuid,
            params: { serviceUuid },
        });
        if (res) {
            message.success("成功删除组织数据服务");
            loadOrganizationServices();
        }
    };

    return {
        ...state,
        loadGateways,
        loadOrganizations,
        loadOrganizationServices,
        setCurrentGateway,
        setCurrentOrganization,
        updateSelectedOrganization,
        updateOrganizationStatus,
        asyncOrganizationInfo,
        deleteOrganization,
        resetInit,
        changeServiceStatus,
        stopService,
        deleteService,
    };
}
